import VueHook from 'alova/vue'
import { createAlova } from 'alova'
import { mockAdapter } from '@/mock'
// import GlobalFetch from 'alova/GlobalFetch'

import type { BaseResponseData } from './types'

export const defaultInstance = createAlova({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  statesHook: VueHook,
  /** @todo 集成后端后使用下一句 以取消生产环境打包mock代码 */
  // requestAdapter: import.meta.env.DEV ? mockAdapter() : GlobalFetch(),
  requestAdapter: mockAdapter(),
  beforeRequest: (method) => {
    const token = localStorage.getItem('token')
    /** @todo token过期处理 */
    if (token) {
      method.config.headers.Authorization = `Bearer ${token}`
    }
  },
  responded: {
    onSuccess: async (response, _method) => {
      if (response.status != 200) {
        throw new Error(response.statusText)
      }

      const data: BaseResponseData<unknown, string> = await response.json()

      return data
    },

    onError: (err, _method) => {
      console.log('error')
      /** @TODO 错误处理 */
      alert(err.message)
    }
  }
})
